local blaze = require "blaze"
local app = require "app"

local M = {}

local log = blaze.logging.get("ui")

local elements = setmetatable({}, { __mode = "k" })

function M.init()
    M.app = app.game.running
end

function M.init_routes()
    local uiconfig = M.app.config.ui
    if uiconfig and uiconfig.routes then
        app.ui.add_routes(uiconfig.routes)
    end
end

function M.activity(base)
    local ret = app.ui.activity(base)
    ret.app = M.app
    return ret
end

function M.element(base)
    local ret = app.ui.element(base)
    ret.app = M.app
    return ret
end

-- 跟踪一个视图组件
-- 在UI模块释放时释放掉
function M.trace_element(element)
    elements[element] = true
end

function M.release()
    local uiconfig = M.app.config.ui
    if uiconfig and uiconfig.routes then
        app.ui.remove_routes(uiconfig.routes)
    end
    for element, _ in pairs(elements) do
        if element.release then
            element:release()
        end
    end
end

return M